package com.hntxk.cqzd.sms.service.impl;



import com.atomikos.icatch.RollbackException;
import com.hntxk.core.framework.model.OperModel;
import com.hntxk.core.framework.model.ResponseModel;
import com.hntxk.core.framework.model.ResultModel;
import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.core.util.ModelEntityUtil;
import com.hntxk.cqzd.sms.model.SmsInfo;
import com.hntxk.cqzd.sms.model.SmsSendee;
import com.hntxk.cqzd.sms.service.SmsInfoService;
import com.hntxk.sp.dict.manager.DictManager;
import com.hntxk.sp.dict.model.Dict;
import com.hntxk.sp.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.UnexpectedRollbackException;

import javax.xml.namespace.QName;
import java.io.FileWriter;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author a
 */
@Service
@Slf4j
public class SmsInfoServiceImpl extends BaseServiceImpl<SmsInfo> implements SmsInfoService {

    public static String  MAPPER_NAMESPACE = "com.hntxk.cqzd.sms.mapper.SmsInfoMapper.";
    @Autowired
    public SmsInfoServiceImpl() {
        super(MAPPER_NAMESPACE);
    }

    /**
     * 获取短信发送记录的内容
     * 包含接收人信息
     *
     * 非管理员账户，只能查询自己发送的短信记录
     * @param infoId 短信记录ID
     * @return
     */
    @Override
    public SmsInfo get(Object infoId) {
        SmsInfo smsInfo = new SmsInfo();
        smsInfo.setInfoId(Long.parseLong(infoId+""));
        if (!LoginUserUtil.isSysAdmin()){
            //当前非管理员账户，只能查询自己发送的短信记录
            smsInfo.setSenderId(LoginUserUtil.getLoginOperatorIdLong());
        }
        smsInfo = super.get(smsInfo);
        if (null == smsInfo){
            return null;
        }
        //查询短信接收人
        smsInfo.setSmsSendee(querySendee(smsInfo.getInfoId()));
        return smsInfo;
    }

    /**
     * 发送短信，同时新增短信发送记录
     * @param model 短信内容
     * @param operInfo logRecord日志
     * @return
     */
    @Override
    public ResultModel<SmsInfo> insert(SmsInfo model, OperModel operInfo) {




        model.setSenderId(LoginUserUtil.getLoginOperatorIdLong());
        model.setSenderName(LoginUserUtil.getLoginUserName());
        model.setSendTime(new Date());

        //保存短信接收人
        for (SmsSendee sendee : model.getSmsSendee()) {
            //主键赋值
            try {
                String encodingStyle = "UTF-8";
//                String targetNamespace = "http://tempuri.org/";
//                String targetNamespace = "http://smsservice/";
                String targetNamespace = DictManager.getInstance().getDict("CQ_SMS_KEY",2).getText();
//                String soapActionURI = "http://localhost:9000/SMSServiceImpl.asmx";
//                String soapActionURI = "http://192.168.200.76:10020/SMSService.asmx";
                String soapActionURI = DictManager.getInstance().getDict("CQ_SMS_KEY",3).getText();
//                String endpoint = "http://localhost:9000/SMSServiceImpl.asmx?wsdl";
//                String endpoint = "http://192.168.200.76:10020/SMSService.asmx?wsdl";
                String endpoint = DictManager.getInstance().getDict("CQ_SMS_KEY",4).getText();
                org.apache.axis.client.Service serviceS = new org.apache.axis.client.Service();
                Call call = (Call) serviceS.createCall();
                call.setSOAPActionURI(soapActionURI);
                call.setTargetEndpointAddress(new java.net.URL(endpoint));
                // WSDL里面描述的接口名称
                call.setOperationName(new QName(targetNamespace,"SendSMS"));
                // 接口的参数
                call.addParameter(new QName(targetNamespace,"msgid"),
                        org.apache.axis.encoding.XMLType.XSD_STRING,
                        javax.xml.rpc.ParameterMode.IN);
                call.addParameter(new QName(targetNamespace,"tel"),
                        org.apache.axis.encoding.XMLType.XSD_STRING,
                        javax.xml.rpc.ParameterMode.IN);
                call.addParameter(new QName(targetNamespace,"msgcontent"),
                        org.apache.axis.encoding.XMLType.XSD_STRING,
                        javax.xml.rpc.ParameterMode.IN);
                call.addParameter(new QName(targetNamespace,"name"),
                        org.apache.axis.encoding.XMLType.XSD_STRING,
                        javax.xml.rpc.ParameterMode.IN);
                call.addParameter(new QName(targetNamespace,"departid"),
                        org.apache.axis.encoding.XMLType.XSD_STRING,
                        javax.xml.rpc.ParameterMode.IN);
                call.addParameter(new QName(targetNamespace,"key"),
                        org.apache.axis.encoding.XMLType.XSD_STRING,
                        javax.xml.rpc.ParameterMode.IN);
                //设置传入服务端的字符集格式如utf-8等
                call.setEncodingStyle(encodingStyle);
                // 设置返回类型*/
                call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
                call.setUseSOAPAction(true);
//                String msgid = UUID.randomUUID().toString().replace("-","");
                String msgid = UUID.randomUUID().toString();
//                empid查询手机号

                String tel = getDasTemplate().selectOne(MAPPER_NAMESPACE+"getTel",sendee.getSendeeId());
                if(tel==null){
                    return ResultModel.of(sendee.getSendeeName()+"未录入手机号");
                }
                String msgcontent = model.getInfoContent();
                String name = sendee.getSendeeName();
                String departid = String.valueOf(sendee.getBranchId());
                Dict dict = DictManager.getInstance().getDict("CQ_SMS_KEY",1);
                String key = String.valueOf(dict.getText());
                String result = (String) call.invoke(new String[] { msgid,tel,msgcontent,name,departid,key });
//              查看返回值写入"D:/token.txt"文件
                /*System.out.println(result);
                FileWriter writer;
                try {
                    writer = new FileWriter("D:/token.txt");
                    writer.write(result);
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }*/

//                 给方法传递参数，并且调用方法
//                System.out.println("result is " + result);
//			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//                xml解析
                /*result = new String(result.getBytes("gbk"), StandardCharsets.UTF_8);
                result=result.substring(1);
//                result = new String(result.getBytes("gbk"), StandardCharsets.UTF_8);
                Document doc = DocumentHelper.parseText(result);
                Element rootElt = doc.getRootElement();*/
                /*if (!"ok".equals(rootElt.getText())){
                    if("短信唯一标识号已存在，请重新输入".equals(rootElt.getText())){
                        return ResultModel.of("短信唯一标识号已存在，请重新输入");
                    }else {
                        return ResultModel.of("key未授权");
                    }
                }*/
                if (!"ok".equals(result)){
                    if("短信唯一标识号已存在，请重新输入".equals(result)){
                        return ResultModel.of("短信唯一标识号已存在，请重新输入");
                    }else {
                        return ResultModel.of("key未授权");
                    }
                }
            }catch (UnexpectedRollbackException e){
                return ResultModel.of("接口超时");
            }
            catch (Exception e) {
                log.error("SMS接口错误",e);
                return ResultModel.of("接口错误");
            }

            getPrimaryKey(sendee);
            sendee.setInfoId(model.getInfoId());
            insert(MAPPER_NAMESPACE+"insertSendee", sendee);
        }
        return super.insert(model, operInfo);
    }

    /**
     * 查询短信发送记录
     * @param model 查询条件
     * @return data
     */
    @Override
    public ResponseModel query2Json(SmsInfo model,boolean enableLike) {

        int maxPageSize = 100;
        if (model.getPagination().getPageSize()>maxPageSize){
            //返回不超过100条记录
            model.getPagination().setPageSize(maxPageSize);
        }
        ResponseModel responseModel = super.query2Json(model,enableLike);
        //查询每条短信记录的接收人
        List<?> data = (List<?>) responseModel.getData();
        for (Object obj : data) {
            model = (SmsInfo) obj;
            model.setSmsSendee(querySendee(model.getInfoId()));
        }
        return responseModel;
    }

    /**
     * 查询短信接收人
     * @param infoId 短信记录ID
     */

    private List<SmsSendee> querySendee(Long infoId) {
        SmsInfo smsInfo = new SmsInfo();
        smsInfo.setInfoId(infoId);
        return  super.query(SmsSendee.class,MAPPER_NAMESPACE + "querySendee", smsInfo, 0, 200);
    }
}
